<template>
    <div class="content_box">
        <h2>{{ title }}</h2>
        <ul>
            <li class="list_item"
                @dblclick="onChangeItem(index)"
                v-for="(item, index) in list"
                :key="index">
                <span v-show="inputShow !== index">{{ item }}</span>
<!--                <input v-show="false" type="text">-->
                <input
                    ref="changeInput"
                    @keydown.enter="onBlur"
                    @blur="onBlur"
                    v-model="list[index]"
                    v-if="inputShow === index"
                    type="text">
                <span @click="onDeleteItem(index)" class="delete_btn">删除</span>
            </li>
        </ul>
    </div>
</template>

<script>
export default {
    name: "ContentBox",
    // props: ["title", "list"],
    props: {
        "title": {
            type: String,
            default: ""
        },
        "list": {
            type: Array,
            default: []
        },
    },
    data(){
        return {
            inputShow: -1,//是否展示input修改框
        }
    },
    //使用了keep-alive之后created destroyed这两个生命周期基本上就没什么用了,更多的时候是使用activated deactivated
 /*   created() {
        //添加对onAddItem事件的监听
        this.$bus.$on("onAddItem", this.onAddItem)
    },
    destroyed() {//移除事件监听
        this.$bus.$off("onAddItem", this.onAddItem)
    },*/

    activated() {
        console.log("组件被显示")
        //添加对onAddItem事件的监听
        this.$bus.$on("onAddItem", this.onAddItem)
    },
    deactivated() {
        console.log("组件被隐藏");
        this.$bus.$off("onAddItem", this.onAddItem)
    },
    methods: {
        //删除
        onDeleteItem(index) {
            this.list.splice(index, 1);
        },
        //添加
        onAddItem(str){
            console.log("contentBox==>str",str);
            //去重
            let reFlag = this.list.some((item)=>{
                return item === str;
            });
            if(reFlag) return alert("请勿重复添加")
            this.list.push(str);
        },
        //双击修改
        onChangeItem(index){
            this.inputShow = index;
            this.$nextTick(_ => {
                this.$refs.changeInput[0].focus()
            });
        },
        //修改移除焦点
        onBlur(){
            this.inputShow = -1;
        }
    }
}
</script>

<style scoped>
.content_box {
    height: 250px;
    border: 2px solid #cccccc;
}

.content_box h2 {
    text-align: center;
}

.list_item {
    position: relative;
    padding: 0 20px;
    height: 30px;
    line-height: 30px;
}

.delete_btn {
    display: none;
    position: absolute;
    right: 20px;
    cursor: pointer;
}

.list_item:hover {
    color: #ffffff;
    background-color: #0000ff;
}

.list_item:hover .delete_btn {
    display: inline-block;
}
</style>